package com.ruoyi.forum.controller;

import com.alibaba.nacos.common.utils.CollectionUtils;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ruoyi.common.core.constant.HttpStatus;
import com.ruoyi.common.core.web.controller.BaseController;
import com.ruoyi.common.core.web.domain.AjaxResult;
import com.ruoyi.common.core.web.page.TableDataInfo;
import com.ruoyi.common.log.annotation.Log;
import com.ruoyi.common.log.enums.BusinessType;
import com.ruoyi.forum.api.vo.CircleBlacklistVO;
import com.ruoyi.forum.api.vo.UserDetail;
import com.ruoyi.forum.domain.CircleBlacklist;
import com.ruoyi.forum.service.AuthServiceExt;
import com.ruoyi.forum.service.CircleBlacklistService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.Parameters;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.dozer.DozerBeanMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import static com.ruoyi.common.security.utils.SecurityUtils.getUsername;

/**
 * @Description:论坛小黑屋controller
 * @Author: Hoda
 * @Date: Create in 2019-09-04
 * @Modified By:
 * @Modified Date:
 */
@Tag(name = "论坛小黑屋", description = "论坛小黑屋管理接口")
@RequestMapping(value = "/circle/blacklist")
@RestController
public class CircleBlackListController extends BaseController {

    @Autowired
    private DozerBeanMapper mapper;

    @Autowired
    private CircleBlacklistService blacklistService;

    @Autowired
    private AuthServiceExt authServiceExt;

    @Log(title = "新增禁言用户", businessType = BusinessType.INSERT)
    @Operation(summary = "新增禁言用户", description = "新增禁言用户")
    @Parameters({
            @Parameter(name = "uid", description = "用户id", required = true),
            @Parameter(name = "days", description = "天数 1-1天 7-7天 30-1月 365-1年", required = true),
            @Parameter(name = "reason", description = "禁言原因", required = true),
    })
    @PostMapping("/add")
    public AjaxResult add(@RequestParam String uid,
                          @RequestParam Integer days,
                          @RequestParam String reason) {
        String operator = getUsername();
        blacklistService.add(uid, days, reason, null, operator);
        return AjaxResult.success();
    }

    @Log(title = "解禁用户", businessType = BusinessType.INSERT)
    @Operation(summary = "解禁用户", description = "解禁用户")
    @Parameters({
            @Parameter(name = "uid", description = "用户id", required = true),
    })
    @PostMapping("/release")
    public AjaxResult release(@RequestParam String uid) {
        String operator = getUsername();
        blacklistService.release(uid, operator);
        return AjaxResult.success();
    }

    @Operation(summary = "获取禁言用户详情", description = "获取禁言用户详情")
    @Parameter(name = "uid", description = "用户id", required = true)
    @GetMapping("/detail")
    public AjaxResult detail(@RequestParam String uid) {
        CircleBlacklist black = blacklistService.getBlackedByUid(uid);
        if (black == null) {
            return AjaxResult.error("用户不在小黑屋");
        }

        CircleBlacklistVO blackVo = mapper.map(black, CircleBlacklistVO.class);
        UserDetail user = authServiceExt.getUserDetail(uid);
        if (user != null) {
            blackVo.setAvatar(user.getPortrait());
            blackVo.setName(user.getName());
            blackVo.setPhone(user.getPhone());
            blackVo.setRegTime(user.getT());
        }
        return AjaxResult.success(blackVo);
    }

    @Operation(summary = "获取禁言用户列表", description = "获取禁言用户列表")
    @Parameters({
            @Parameter(name = "pageNum", description = "页码", example = "1"),
            @Parameter(name = "pageSize", description = "条数", example = "10")
    })
    @GetMapping("/list")
    public TableDataInfo list(@RequestParam(required = false) Integer status,
                              @RequestParam(required = false, defaultValue = "1") Integer pageNum,
                              @RequestParam(required = false, defaultValue = "10") Integer pageSize) {
        // 使用 LambdaQueryWrapper 构造查询条件
        LambdaQueryWrapper<CircleBlacklist> wrapper = new LambdaQueryWrapper<>();
        wrapper
                .eq(status != null, CircleBlacklist::getStatus, status)
                .orderByDesc(CircleBlacklist::getCreateTime);

        // 构造分页对象
        Page<CircleBlacklist> page = new Page<>(pageNum, pageSize);
        page = blacklistService.page(page, wrapper);

        List<CircleBlacklistVO> voList = new ArrayList<>();
        if (CollectionUtils.isNotEmpty(page.getRecords())) {
            voList = page.getRecords().stream()
                    .map(black -> mapper.map(black, CircleBlacklistVO.class))
                    .collect(Collectors.toList());

            Map<String, UserDetail> userMap = authServiceExt.getUserMapByUidList(voList.stream()
                    .map(CircleBlacklistVO::getUid)
                    .distinct()
                    .collect(Collectors.toList()));

            voList.forEach(vo -> {
                if (userMap.containsKey(vo.getUid())) {
                    UserDetail user = userMap.get(vo.getUid());
                    vo.setAvatar(user.getPortrait());
                    vo.setPhone(user.getPhone());
                    vo.setEmail(user.getEmail());
                    vo.setName(user.getName());
                }
            });
        }
        TableDataInfo result = new TableDataInfo(voList, page.getTotal());
        result.setCode(HttpStatus.SUCCESS);
        result.setMsg("查询成功");
        return result;
    }


    @Operation(summary = "获取禁言用户详情", description = "获取禁言用户详情")
    @Parameter(name = "id", description = "禁言用户id", required = true)
    @GetMapping("/getById/{id}")
    public AjaxResult getById(@PathVariable("id") Long id){
        CircleBlacklist circleBlacklist = blacklistService.getById(id);
        return AjaxResult.success(circleBlacklist);
    }
}